// 收到2开头的消息
import { resArr } from '../socketOnMessageTools'
import { Message } from 'element-ui'
import { ifContactInList, dealMessage, decryptMessage } from '../socketTools'
import store from '@/store'
import tools from '@/utils/tools'
import router from '@/router'

// 解析消息
const decryptMsg = decryptMessage
// 判断缓存的用户列表中是否有该用户
const ifContactInContactlist = ifContactInList
// 处理消息
const dealMsg = dealMessage

const dataDealer = tools.dataDealer

export default async (type, result) => {
  switch (type) {
    // 通话-收到通话邀请
    case '2.1.2': {
      decryptMsg(result.body, ['call_type', 'from', 'msg_id'], 0)
      const realData = resArr[0]
      if (!store.state.common.ifShowVideoInvitation) {
        await ifContactInContactlist(realData.from, 1)
        store.commit('message/set_videoCallInfo', {
          isInviter: false,
          oppositeID: realData.from
        })
        store.commit('common/set_ifShowVideoInvitation', true)
        store.commit('message/set_videoCallMsgID', realData.msg_id)
      }
      break
    }
    // 通话-邀请已被取消
    case '2.1.4': {
      decryptMsg(result.body, ['from', 'msg_id'], 0)
      const realData = resArr[0]
      if (store.state.message.videoCallInfo.oppositeID === realData.from && store.state.message.videoCallMsgID === realData.msg_id) {
        store.dispatch('chatInformation/setAddMessage', {
          message: {
            id: realData.from,
            isSelf: false,
            msg_id: realData.msg_id,
            type: 'videoCall',
            timestamp: +new Date(),
            callState: 1
          },
          id: realData.from,
          idType: 1
        })
        store.commit('chatInformation/set_topContact', {
          id: store.state.message.videoCallInfo.oppositeID,
          id_type: 1
        })
        store.commit('message/set_videoCallInfo', {
          isInviter: null,
          oppositeID: null
        })
        store.commit('common/set_ifShowVideoInvitation', false)
        store.commit('message/set_videoCallMsgID', null)
      }
      break
    }
    // 通话-通话邀请已被接受
    case '2.1.6': {
      decryptMsg(result.body, ['msg_id'], 0)
      const realData = resArr[0]
      if (store.state.message.videoCallMsgID === realData.msg_id) {
        // 将该视频通话的msg_id作为房间ID用来防止路由随意跳转
        store.commit('conferenceRoom/set_cf_id', realData.msg_id)
        // 将房间类型设置为videoCall
        store.commit('conferenceRoom/set_cf_type', 'videoCall')
        // 将房间设置自动配置 摄像头必开
        store.commit('conferenceRoom/set_conferenceSettings', {
          voiced: true,
          camera: true,
          durationOfAttendance: true
        })
        // 房间用户设置
        store.commit('conferenceRoom/set_cf_members', [
          {
            id: tools.getUserId(),
            voiced: true,
            camera: true,
            stream: new MediaStream()
          },
          {
            id: store.state.message.videoCallInfo.oppositeID,
            voiced: true,
            camera: true,
            stream: new MediaStream()
          }
        ])
        // 设置通话开始时间
        store.commit('conferenceRoom/set_cf_start_time', +new Date())
        // 跳转路由
        router.push('/videoCall')
        const oppositeUser = JSON.parse(JSON.stringify(store.state.message.videoCallInfo))
        // 打开摄像头
        tools.webRTC.openMedia({}).then(stream => {
          // 与对方建立peerconnection
          tools.webRTC.getPeerConnection(oppositeUser.oppositeID).then(peer => {
            // peer关联本地流
            tools.webRTC.addTracks(peer, stream)
            // 发送offer
            tools.webRTC.createOffer(peer, realData.msg_id, oppositeUser.oppositeID)
          })
        })
        store.commit('common/set_ifShowVideoInvitation', false)
        store.commit('message/set_videoCallMsgID', null)
      }
      break
    }
    // 通话-通话邀请已被拒绝
    case '2.1.8': {
      decryptMsg(result.body, ['msg_id'], 0)
      const realData = resArr[0]
      if (store.state.message.videoCallMsgID === realData.msg_id) {
        store.dispatch('chatInformation/setAddMessage', {
          message: {
            isSelf: true,
            msg_id: realData.msg_id,
            type: 'videoCall',
            timestamp: +new Date(),
            callState: 2
          },
          id: store.state.message.videoCallInfo.oppositeID,
          idType: 1
        })
        store.commit('chatInformation/supplement_msgId', {
          id: store.state.message.videoCallInfo.oppositeID,
          idType: 1,
          msgID: realData.msg_id
        })
        store.commit('chatInformation/set_topContact', {
          id: store.state.message.videoCallInfo.oppositeID,
          id_type: 1
        })
        store.commit('message/set_videoCallInfo', {
          isInviter: null,
          oppositeID: null
        })
        store.commit('common/set_ifShowVideoInvitation', false)
        store.commit('message/set_videoCallMsgID', null)
      }
      break
    }
    // 通话-通话被挂断
    case '2.1.10': {
      // 此处id_type用作reason解密
      decryptMsg(result.body, ['id_type', 'msg_id'], 0)
      const realData = resArr[0]
      if (realData.msg_id === store.state.conferenceRoom.cf_id) {
        const startTime = store.state.conferenceRoom.cf_start_time
        // 将消息塞入与对方的聊天列表中
        store.dispatch('chatInformation/setAddMessage', {
          message: {
            id: store.state.message.videoCallInfo.isInviter ? '' : store.state.message.videoCallInfo.oppositeID,
            isSelf: store.state.message.videoCallInfo.isInviter,
            msg_id: store.state.conferenceRoom.cf_id,
            type: 'videoCall',
            timestamp: +new Date(),
            callState: 5,
            duration: Math.floor((+new Date() - startTime) / 1000)
          },
          id: store.state.message.videoCallInfo.oppositeID,
          idType: 1
        })
        store.commit('chatInformation/supplement_msgId', {
          id: store.state.message.videoCallInfo.oppositeID,
          idType: 1,
          msgID: store.state.conferenceRoom.cf_id
        })
        store.commit('chatInformation/set_topContact', {
          id: store.state.message.videoCallInfo.oppositeID,
          id_type: 1
        })
        // 关闭所有的peer通道
        store.commit('conferenceRoom/close_allPeer')
        // 还原会议室初始状态
        store.commit('conferenceRoom/reset_state')
        // 清空视频通话存储的对方信息
        store.commit('message/set_videoCallInfo', {
          isInviter: null,
          oppositeID: null
        })
        // 跳转消息页
        router.push('/message')
        Message({
          type: 'info',
          message: realData.id_type === 0 ? '通话已结束' : '网络异常，通话已结束'
        })
      }
      break
    }
    // 通话-收到P2P消息
    case '2.1.11': {
      decryptMsg(result.body, ['p2p_type', 'id_length', 'msg_id', 'p2p_msg'], 0)
      const realData = resArr[0]
      switch (realData.p2p_type) {
        // 收到offer
        case 1: {
          // 对方信息
          const oppositeUser = store.state.conferenceRoom.cf_members.filter(item => !tools.isSelf(item.id))[0]
          // 判断是否已经为对方建立peerConnection
          if (oppositeUser.peer) {
            const sdp = realData.p2p_msg
            tools.webRTC.createAnswer(oppositeUser.peer, sdp, realData.msg_id, oppositeUser.id)
          } else {
            const timer = setInterval(() => {
              const oppoUser = store.state.conferenceRoom.cf_members.filter(item => !tools.isSelf(item.id))[0]
              if (oppoUser.peer) {
                const sdp = realData.p2p_msg
                tools.webRTC.createAnswer(oppoUser.peer, sdp, realData.msg_id, oppoUser.id)
                clearInterval(timer)
              }
            }, 100)
          }
          break
        }
        // 收到answer
        case 2: {
          const peer = store.state.conferenceRoom.cf_members.filter(item => !tools.isSelf(item.id))[0].peer
          const sdp = realData.p2p_msg
          tools.webRTC.createRemoteSDP(peer, sdp)
          break
        }
        // 收到iceCandidate
        case 3: {
          const sdpMid = realData.p2p_msg.candidate_type === 1 ? '0' : '1'
          const sdpMLineIndex = realData.p2p_msg.candidate_type === 1 ? 0 : 1
          const candidate = realData.p2p_msg.candidate_content
          store.commit('conferenceRoom/add_iceCandidate', {
            id: store.state.conferenceRoom.cf_members.filter(item => !tools.isSelf(item.id))[0].id,
            sdpMid,
            sdpMLineIndex,
            candidate
          })
          break
        }
        // 收到重连
        case 4: {
          const oppoUser = store.state.conferenceRoom.cf_members.filter(item => !tools.isSelf(item.id))[0]
          store.commit('conferenceRoom/close_peer', oppoUser.id)
          store.commit('conferenceRoom/reset_mediaStream', oppoUser.id)
          tools.webRTC.getPeerConnection(oppoUser.id).then(peer => {
            if (tools.webRTC.getLocalStream().active) {
              tools.webRTC.addTracks(peer, tools.webRTC.getLocalStream())
              // 发送offer
              tools.webRTC.createOffer(peer, realData.msg_id, oppoUser.id)
            } else {
              tools.webRTC.openMedia({}).then(stream => {
                tools.webRTC.addTracks(peer, stream)
                // 发送offer
                tools.webRTC.createOffer(peer, realData.msg_id, oppoUser.id)
              })
            }
          })
          break
        }
      }
      break
    }
    // 通话-对方关闭摄像头
    case '2.1.12': {
      decryptMsg(result.body, ['msg_id'], 0)
      const realData = resArr[0]
      if (store.state.conferenceRoom.cf_id === realData.msg_id) {
        store.commit('conferenceRoom/set_cf_member_device', {
          id: store.state.message.videoCallInfo.oppositeID,
          type: 'camera',
          status: false
        })
      }
      break
    }
    // 通话-对方打开摄像头
    case '2.1.13': {
      decryptMsg(result.body, ['msg_id'], 0)
      const realData = resArr[0]
      if (store.state.conferenceRoom.cf_id === realData.msg_id) {
        store.commit('conferenceRoom/set_cf_member_device', {
          id: store.state.message.videoCallInfo.oppositeID,
          type: 'camera',
          status: true
        })
      }
      break
    }
    // 私聊-收到文本消息
    case '2.2.2': {
      decryptMsg(result.body, ['id', 'timestamp', 'msg_length', 'msg', 'msg_id'], 0)
      const msgObj = { ...resArr[0], isSelf: false, type: 'words' }
      // 如果用户缓存列表中没有该用户
      await ifContactInContactlist(msgObj.id, 1)
      // 处理消息
      dealMsg(msgObj, 1)
      break
    }
    // 私聊-收到语音消息
    case '2.2.4': {
      decryptMsg(result.body, ['id', 'timestamp', 'file_id', 'voice_length', 'msg_id'], 0)
      const realData = resArr[0]
      const msgObj = {
        ...realData,
        voiceSrc: await store.dispatch('file/downloadFile', {
          fileType: 4,
          fileID: realData.file_id,
          other: realData.id
        }),
        listened: false,
        isSelf: false,
        type: 'voice'
      }
      // 如果用户缓存列表中没有该用户
      await ifContactInContactlist(msgObj.id, 1)
      // 处理消息
      dealMsg(msgObj, 1)
      break
    }
    // 私聊-收到图片消息
    case '2.2.6': {
      decryptMsg(result.body, ['id', 'timestamp', 'img_id', 'img_width', 'img_height', 'msg_id'], 0)
      const realData = resArr[0]
      const msgObj = {
        ...realData,
        imgSrc: dataDealer.blobToUrl(await store.dispatch('file/downloadFile', {
          fileType: 4,
          fileID: realData.img_id,
          other: realData.id
        })),
        isSelf: false,
        type: 'pic'
      }
      // 如果用户缓存列表中没有该用户
      await ifContactInContactlist(msgObj.id, 1)
      // 处理消息
      dealMsg(msgObj, 1)
      break
    }
    // 私聊-收到文件消息
    case '2.2.8': {
      decryptMsg(result.body, ['id', 'timestamp', 'file_id', 'file_size', 'file_name_length', 'file_name', 'msg_id'], 0)
      const realData = resArr[0]
      const msgObj = {
        ...realData,
        isSelf: false,
        type: 'file'
      }
      // 如果用户缓存列表中没有该用户
      await ifContactInContactlist(msgObj.id, 1)
      // 处理消息
      dealMsg(msgObj, 1)
      break
    }
  }
}
